<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 经纪人 脚本
 */
class Cron_INVITE extends CI_Controller {
	private $redis;
	private $Referrals;
	private $cnyClass;
	private $logFile;
	private $cfdClass;
	public function __construct(){  
        parent::__construct();
        if(!is_cli()){
        	header("HTTP/1.0 404 Not Found");
        	show_error('Not Found',404);
        	die;
        }

		//加载CFD操作类
		$this->load->library('Cny_Class');
		$this->cnyClass = $this->cny_class;

        //加载分成操作类
		$this->load->library('Referrals');
		$this->Referrals = $this->referrals;

		$this->load->config('cfd');
		$this->load->library('cfdClass');
		$this->cfdClass = $this->cfdclass;
    }

    /**
     * 交易分成
     * @return [type] [description]
     */
	public function addInvite(){
		$symbol	=	"DAOUSD";
		if(!$this->cfdClass->setProduct($symbol,'IB')){//设置产品
			die("无效操作！");
		}
		$productData = $this->cfdClass->getProductData();
		$settlementArr = explode(',',$productData['settlement']);
		$dst = $this->cfdClass->checkDST($symbol);
		$cur_H			=	date('H');
		$settlement_H	=	date('H',strtotime($settlementArr[$dst]));
		if($cur_H !=$settlement_H){
			die("结算时间：".$settlement_H);
		}
		
		$this->load->library('Statistics');
		$date	=	date("Y-m-d",strtotime("-1 days"));
		$dst	=	$this->statistics->getDst($date);
		if(empty($dst)){
			die("结算时间获取不到！");
		}

		$sdate		=	date("Y-m-d ".($settlement_H+1).":00:00",strtotime($date));
		$edate		=	date("Y-m-d ".$settlement_H.":59:59",strtotime($date)+24*3600);
		echo $sdate."-".$edate."\n";

		$trade['where']		=	array('dtype'=>'cny');
		$trade['source_in']	=	array('10001','50001');
		$rate				=	"0.01";

		$vip_arr	=	$this->Referrals->getInviteAllVip();
		$vip_list	=	array();
		if(!empty($vip_arr))foreach($vip_arr as $arr){
			$vip_list[$arr['uid']]	=	$arr['uid'];
		}
		unset($vip_arr);

		$invite_arr	=	$this->Referrals->getInvite();
		if(!empty($invite_arr))foreach($invite_arr as $arr){
			if(!isset($vip_list[$arr['master']])){
				$invite_list[$arr['slave']]	=	$arr['master'];
			}
		}
		unset($invite_arr);
		
		$this->load->model('cfd_model');
		$statistics	=	$this->cfd_model->getTradeStatistics($trade,$sdate,$edate);
		$deal		=	array();
		if(!empty($statistics))foreach($statistics as $items){
			if(!empty($invite_list[$items['uid']])){
				$master							=	$invite_list[$items['uid']];
				$deal[$master][$items['uid']]	=	isset($deal[$master][$items['uid']])?bcadd($items['cash'],$deal[$master][$items['uid']],2):$items['cash'];
			}
		}
		unset($invite_list);
		unset($statistics);
		
		$this->db	= $this->load->database('default',true);
		$this->load->config('cny');
		$source = $this->config->item('invite_source');

		$datetime	= date("Y-m-d H:i:s");
		if(!empty($deal)) foreach($deal as $master=>$v){
			try {
				$this->db->trans_start();//开始事务
				
				$total_cny	=	$total_trade_cny	=	0;
				foreach($v as $slave=>$trade_cny){
					$cny		=	bcmul($trade_cny,$rate,2);
					$total_cny	=	bcadd($total_cny,$cny,2);
					$log_arr	=	array(
						'master'	=>	$master,
						'slave'		=>	$slave,
						'cny'		=>	$cny,
						'trade_cny'	=>	$trade_cny,
						'rate'		=>	$rate,
						'date'		=>	$sdate,
						'create_time'=>	$datetime,
					);
					$log_table	=	"invite_details";
					if (!$this->db->insert($log_table,$log_arr)) throw new Exception('L:'.__LINE__.' 添加分成明细失败!', 1);
					$where = array('master'=>$master,'slave'=>$slave);
					$this->db->set('cny', 'cny+'.$cny, FALSE);
					$this->db->where($where);
					
					if(!$this->db->update('invite')){
						throw new Exception('L:'.__LINE__." 更新提成总额失败！", 1);
					}
				}
				
				$add_arr  =  array(
					'uid'=> $master,
					'name' => 'ACCOUNT',//帐户
					'use_value' => $total_cny,
					'source' => $source,
					'add_time' => date("Y-m-d H:i:s"),
				);
				
				if(!$this->cnyClass->add($add_arr)){
					throw new Exception('L:'.__LINE__." 添加用户提成失败！", 1);
				}
				$this->db->trans_complete();
				$this->cnyClass->flushUserCache($master);
				writeDebug('['.$datetime.'] invite: '.$master.':'.$total_cny.' 处理完成!', 'Cron_INVITE');
			} catch (Exception $e) {
				writeDebug('['.$datetime.'] invite: '.$master.':'.$total_cny.' 处理失败! Err:'.$e->getMessage(), 'Cron_INVITE');
				$this->db->trans_rollback();
			}
		}
		echo "over";
	}
	
	/**
     * VIP经纪人分成
     * @return [type] [description]
     */
	public function vipInvite(){
		$rate	=	"0.4";
		$sdate	=	$this->Referrals->getLastVipDate();
		if(!$sdate){
			$sdate	=	'2016-08-01';
		}else{
			$sdate	=	date("Y-m-d",strtotime($sdate)+24*3600);
		}

		$edate		=	date("Y-m-d",strtotime($sdate)+9*24*3600);
		$now_date	=	date("Y-m-d",strtotime("-1 days"));
		echo $sdate."-".$edate."\n";
		if($edate <= $now_date){
			$this->load->library('Statistics');
			//计算前29天交易额或盈亏
			$trade				=	array('1'=>'1');
			$tradeStatistics	=	$this->statistics->getTrade($trade,$sdate);
			$vip_list			=	array();
			if(!empty($tradeStatistics)) foreach($tradeStatistics as $items){
				if($items['master']==0) continue;
				if(!$this->Referrals->getInviteVip($items['master'])) continue;

				$invite	=	$this->referrals->getInviteCnyByMaster($items['uid']);
				$yk		=	bcadd($items['ticket_yk'],$items['yk'],2);
				$yk		=	!empty($invite)?bcsub($yk,$invite['cny'],2):$yk; 
				$vip_list[$items['master']]	=	isset($vip_list[$items['master']])?bcadd($vip_list[$items['master']],$yk,2):$yk;	
			}

			$db	= $this->load->database('default',true);
			if(!empty($vip_list))foreach($vip_list as $master=>$yk){
				if($yk=='0.00')continue;

				$cny	=	bcmul($yk,$rate,2);
				try {
					$db->trans_start();//开始事务
					
					$log_arr	=	array(
						'master'	=>	$master,
						'cny'		=>	$cny,
						'yk'		=>	$yk,
						'rate'		=>	$rate,
						'sdate'		=>	$sdate,
						'edate'		=>	$edate,
						'create_time'=>	$datetime,
					);
					$log_table	=	"invite_vip_details";
					if (!$db->insert($log_table,$log_arr)) throw new Exception('L:'.__LINE__.' 添加分成明细失败!', 1);

					$where = array('uid'=>$uid);
					$db->set('cny', 'cny+'.$cny, FALSE);
					$db->where($where);
					
					if(!$db->update('invite_vip')){
						throw new Exception('L:'.__LINE__." 更新提成总额失败！", 1);
					}
					
					$db->trans_complete();
					writeDebug('['.$datetime.'] vip_invite: '.$master.':'.$cny.' 处理完成!', 'Cron_INVITE');
				} catch (Exception $e) {
					writeDebug('['.$datetime.'] vip_invite: '.$master.':'.$cny.' 处理失败! Err:'.$e->getMessage(), 'Cron_INVITE');
					$db->trans_rollback();
				}
			}
		}
	}
}
